<template>
	<view>
		<uni-nav-bar ref="navBar" fixed statusBar title="发布商品" :border="false" backgroundColor="#ffffff" @clickLeft="goBack">
			<template v-slot:left>
				<image src="@/static/svg/publicSvg/icon-back.svg" />
			</template>
		</uni-nav-bar>
		<view :style="{'height':h}" class="goods-dec">
			<view>
				<view class="goods-title">商品标题</view>
				<view class="goods-name">
					<input type="text" placeholder="*请输入商品标题(最多50字)" :maxlength="50" v-model="formData.goodsName">
				</view>
			</view>

			<view class="">
				<view class="goods-title">商品图片</view>
				<view class="goods-img">
					<uni-file-picker limit="1" :imageStyles="imageStyles" :auto-upload="false" v-model='fileLists'
						@select="selectImg" ref="imgPicker">
						<view class="pick">
							+
						</view>
					</uni-file-picker>
				</view>
			</view>
			<view>
				<view class="goods-title">商品信息</view>
				<view class="goods-price-list">
					<view class="price-item flex justify-between">
						<view >
							<view class="goods-price-name">商品售价</view>
							<view class="fs-12 c3-6">商品售价指参与活动后，商户需要收回的商品成本，若策划人自己做活动，商品售价建议0元，无需向商户分账，活动收入全部归属于策划人</view>
						</view>
						<input class="price-num" type="digit" placeholder="请输入商品售价" v-model="formData.goodsPrice" style="min-width: 110px;">
					</view>
					<view class="price-item flex justify-between">
						<text class="goods-price-name">划线价格</text>
						<input class="price-num" type="digit" placeholder="请输入划线价格" v-model="formData.originPrice">
					</view>
					<view class="price-item flex justify-between">
						<text class="goods-price-name">库存</text>
						<input class="price-num" type="number" :maxlength="8"  placeholder="请输入商品库存" v-model="formData.totalStock">
					</view>
					<view v-if="formData.businessName" class="price-item flex justify-between">
						<text class="goods-price-name">创建人</text>
						<text class="goods-price-name">{{formData.businessName}}</text>
					</view>
				</view>
			</view>
			<view>
				<view class="" v-if="formData.verifyType == 0">
					<view class="goods-title">票付通</view>
					<view class="goods-price-list">
						<view class="price-item flex item-center justify-between">
							<text class="goods-price-name">开启即表示商品需通过票付通进行核销</text>
							<uv-switch size="16" v-model="formData.verifyType"  :inactiveValue="0" :activeValue="1" inactiveColor="#CCCCCC" activeColor="#00AEFF"></uv-switch>
						</view>
					</view>
				</view>
				<view v-else>
					<view class="goods-title flex justify-between">
						<view class="">票付通</view>
						<uv-switch size="16" v-model="formData.verifyType"  :inactiveValue="0" :activeValue="1" inactiveColor="#CCCCCC" activeColor="#00AEFF"></uv-switch>
					</view>
					<view class="goods-title-dec">开启即表示商品需通过票付通进行核销</view>
					
				</view>
				<view class="goods-price-list" v-show="formData.verifyType == 1">
					<view class="price-item flex justify-between">
						<text class="goods-price-name">供应商ID</text>
						<input class="price-num" type="number" :maxlength="49" placeholder="请输入供应商ID" v-model="formData.pftSupplier">
					</view>
					<view class="price-item flex justify-between">
						<text class="goods-price-name">票付通产品ID</text>
						<input class="price-num" type="number" :maxlength="49" placeholder="请输入票付通产品ID" v-model="formData.pftProduct">
					</view>
					<view class="price-item flex justify-between">
						<text class="goods-price-name">票付通门票ID</text>
						<input class="price-num" type="number" :maxlength="49" placeholder="请输入票付通门票ID" v-model="formData.pftTicket">
					</view>
				</view>
			</view>
			<view class="">
				<view class="goods-title">使用说明</view>
				<textarea name="" placeholder="请输入使用说明" id="" cols="30" rows="10" class="goods-details" v-model="formData.details"></textarea>
			</view>
		</view>
		<view class="btn-box flex justify-between">
			<view class="btn-gary" @click="sendSubmit(2)">保存至待发售</view>
			<view class="btn-red" @click="sendSubmit(3)">发布并上架商品</view>
		</view>
		<!-- 普通弹窗 -->
		<uni-popup ref="popup" type="bottom">
			<view class="pop-box flex flex-col item-center">
				<view class="pop-alert">!</view>
				<view class="pop-title">退出发布产品</view>
				<view class="pop-text">保存后可在草稿箱中继续编辑</view>
				<view class="pop-btn-box flex justify-between">
					<view class="pop-btn" @click="callBack">退出</view>
					<view class="pop-btn pop-red" @click="sendSubmit(1)">保存并退出</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup name="releaseGoods">
	import {
		ref,
		watch,
		onMounted,
		reactive,
		defineComponent,
		getCurrentInstance
	} from 'vue'
	import {
		mathHeight,
		judegDit
	} from '@/utils/index.js'
	import {
		uploadFileApi
	} from '@/api/common.js'
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import {
		releaseGoods,
		deleteGoods,
		editGoods
	} from '@/center/api/goods.js'
	import {
		useUserStore
	} from '@/stores/modules/user.js'
	const userStore = useUserStore()
	const userInfo = userStore.userInfo
	const h = mathHeight(140)
	const imageStyles = reactive({
		width: 80,
		height: 80,
		border: {
			radius: 12,
			color: 'rgba(51,51,51,.61)',
			style: 'dashed'
		}
	})
	let fileLists = ref([])
	const popup = ref()
	let formData = ref({
		details: '',
		goodsImgs: '',
		goodsName: '',
		goodsPrice: '',
		goodsState: '',
		merchantId: '',
		originPrice: '',
		totalStock: '',
		verifyType: 0,
		pftProduct: '',
		pftSupplier: '',
		pftTicket: ''
	})
	const imgPicker = ref()
	const selectImg = async (e) => {
		let tempFiles = e.tempFiles[0]
		let files = e.tempFilePaths
		if (tempFiles.size > 5 * 1024 * 1024) {
			uni.showToast({
				icon: 'none',
				title: '图片不可大于5M'
			})
			fileLists.value = []
			return
		}
		uploadFileApi(3, {
			filePath: files[0],
			name: 'file'
		}).then(result => {
			if (result.code == 200) {
				let item = {
					url: result.data,
					name: tempFiles.name,
					extname: tempFiles.extname
				}
				fileLists.value = [item]
			} else {
				uni.showToast({
					icon: 'none',
					title: result.message
				})
				fileLists.value = []
			}
		}).catch(err => {
			uni.showToast({
				icon: 'none',
				title: err.message
			})
			fileLists.value = []
		})

	}
	let getOpenerEventChannel = ref(null)
	onLoad((params) => {
		getOpenerEventChannel.value = getCurrentInstance().ctx.getOpenerEventChannel()
		// console.log(getOpenerEventChannel.value,'getOpenerEventChannel.value')
		getOpenerEventChannel.value.on('acceptData', data => {
			formData.value = data.data
			if (data.data.goodsImgs) {
				var url = data.data.goodsImgs
				var lastOf = url.lastIndexOf('/') // '/'所在的最后位置
				var str = url.substr(lastOf + 1) //截取文件名称和后缀   输出：挽风.jpg
				var strUrl = url.substr(0, lastOf) //截取路径字符串    输出：http://localhost:5613/static
				var pName = str.substring(0, str.lastIndexOf(".")) //截取文件名   输出：挽风
				var suffix = url.substring(url.lastIndexOf(".")) //截取后缀   输出：.jpg
				var suffixType = url.substring(url.lastIndexOf(".") + 1) //截取后缀名  输出：jpg
				fileLists.value = [{
					"name": str,
					"extname": suffixType,
					url: data.data.goodsImgs
				}]
			}
		})
	})
	// const judegDit = (num) =>{
	// 	var reg= /^(-?\d+)(\.\d{1,2})?$/
	// 	if(reg.test(num+''))
	// 	{
	// 		return true
	// 	}else{
	// 		return false
	// 	}
	// }
	// getCurrentInstance().proxy.getOpenerEventChannel().emit('reFreshPage','refresh111')
	const sendSubmit = async (goodsState) => {
		popup.value.close('bottom')
		if (goodsState != 1) {
			const msgList = {
				goodsName:'请填写商品名称',
				goodsPrice:'请填写商品售价',
				originPrice:'请填写划线价格',
				fileLists:'请选择商品图片',
				totalStock:'请填写商品库存',
				details:'请填写使用说明'
			}
			if (!formData.value.goodsName){
				uni.showToast({
					icon: 'none',
					title:msgList.goodsName
				})
				return
			}
			if(!fileLists.value.length){
				uni.showToast({
					icon: 'none',
					title:msgList.fileLists
				})
				return
			}
			if (!formData.value.goodsPrice){
				uni.showToast({
					icon: 'none',
					title:msgList.goodsPrice
				})
				return
			}
			if(!judegDit(formData.value.goodsPrice)){
				uni.showToast({
					icon: 'none',
					title:'商品售价至多只可保留两位小数',
				})
				return
			}
			// if(Number(formData.value.goodsPrice)>99999999 || Number(formData.value.goodsPrice)<1){
			// 		uni.showToast({
			// 			icon: 'none',
			// 			title:'商品售价需在1-99999999元之间',
			// 		})
			// 		return
			// }
			if(formData.value.originPrice){
				if(!judegDit(formData.value.originPrice)){
					uni.showToast({
						icon: 'none',
						title:'划线价格至多只可保留两位小数',
					})
					return
				}
				if(Number(formData.value.originPrice)>99999999 || Number(formData.value.originPrice)<1){
						uni.showToast({
							icon: 'none',
							title:'划线价格需在1-99999999元之间',
						})
						return
				}
				if((Number(formData.value.originPrice) < Number(formData.value.goodsPrice))){
					uni.showToast({
						icon: 'none',
						title:'划线价格必须大于等于商品售价'
					})
					return
				}
				
			}
			if (!formData.value.totalStock){
				uni.showToast({
					icon: 'none',
					title:msgList.totalStock
				})
				return
			}
			if (!formData.value.details){
				uni.showToast({
					icon: 'none',
					title:msgList.details
				})
				return
			}
			if(formData.value.verifyType == 1){
				if(!formData.value.pftSupplier){
					uni.showToast({
						icon: 'none',
						title: '请填写供应商ID'
					})
					return
				}
				if(!formData.value.pftProduct){
					uni.showToast({
						icon: 'none',
						title: '请填写票付通产品ID'
					})
					return
				}
				if(!formData.value.pftTicket){
					uni.showToast({
						icon: 'none',
						title: '请填写票付通门票ID'
					})
					return
				}
			}
		}else if(goodsState == 1){
			if(formData.value.goodsPrice){
				if(!judegDit(formData.value.goodsPrice)){
					uni.showToast({
						icon: 'none',
						title:'商品售价至多只可保留两位小数',
					})
					return
				}
				if(Number(formData.value.goodsPrice)>99999999 || Number(formData.value.goodsPrice)<1){
						uni.showToast({
							icon: 'none',
							title:'商品售价需在1-99999999元之间',
						})
						return
				}
				
			}
			if(formData.value.originPrice){
				if(!judegDit(formData.value.originPrice)){
					uni.showToast({
						icon: 'none',
						title:'划线价格至多只可保留两位小数',
					})
					return
				}
				if(Number(formData.value.originPrice)>99999999 || Number(formData.value.originPrice)<1){
						uni.showToast({
							icon: 'none',
							title:'划线价格需在1-99999999元之间',
						})
						return
				}
				if(formData.value.goodsPrice && (Number(formData.value.originPrice) < Number(formData.value.goodsPrice))){
					uni.showToast({
						icon: 'none',
						title:'划线价格必须大于等于商品售价'
					})
					return
				}
				
			}
		}
		
		let form = JSON.parse(JSON.stringify(formData.value))
		let list = []
		if (fileLists.value && fileLists.value.length) {
			fileLists.value.forEach((item) => {
				list.push(item.url)
			})
			form.goodsImgs = list.join(',')
		}
		uni.showLoading()
		form.goodsState = goodsState
		form.merchantId = userInfo.id
		let result = null
		if (form.id) {
			result = await editGoods(form)
		} else {
			result = await releaseGoods(form)
		}
		uni.hideLoading()
		if (result) {
			setTimeout(()=> {
				uni.showToast({
					icon: 'none',
					title: goodsState == 1 ? '保存成功' : goodsState == 2 ? '保存成功' : '上架成功',
					complete() {
						setTimeout(() => {
							getOpenerEventChannel.value.emit('reFreshPage', 'refresh')
							uni.navigateBack({
								delta: 1
							})
						}, 1000)
					}
				})
			},500)
		} else {
			uni.showToast({
				icon: 'none',
				title: '保存失败，请稍后再试'
			})
		}
	}
	
	// console.log(getOpenerEventChannel(),'getOpenerEventChannel()')
	const goBack = () => {
		// console.log(fileLists,'fileLists.value')
		if (formData.value.goodsName || formData.value.goodsPrice || formData.value.originPrice || formData.value.totalStock || formData.value.details || (fileLists.value && fileLists.value.length)) {
			popup.value.open('bottom')
		} else {
			uni.navigateBack()
		}
	}
	const callBack = () => {uni.navigateBack()}
</script>

<style lang="scss" scoped>
	.goods-dec {
		background-color: #ffffff;
		padding: 20px;
		overflow-y: auto;

		.goods-title {
			font-family: PingFang SC;
			font-size: 14px;
			font-weight: 600;
			line-height: 20px;
			color: #333333;
			margin-top: 20px;
		}
		.goods-title-dec{
			font-family: PingFang SC;
			font-size: 12px;
			font-weight: 400;
			line-height: 17px;
			color: rgba(51, 51, 51, 0.6);
			margin-top: 4px;
		}
	}

	.btn-box {
		padding: 20px;
		background-color: #ffffff;

		.btn-gary,
		.btn-red {
			width: 40%;
			height: 46px;
			padding: 12px, 45px, 12px, 45px;
			border-radius: 8px;
			border: 1px solid #333333;
			color: #333333;
			text-align: center;
			line-height: 46px;
		}

		.btn-red {
			background: #FA4543;
			color: #ffffff;
			border-color: #FA4543;
		}
	}

	.goods-name {
		margin: 10px 0;
		height: 44px;
		border-radius: 12px;
		background: #F5F5F5;
		padding: 12px;
		font-family: PingFang SC;
		font-size: 14px;
		font-weight: 400;
		line-height: 20px;
	}

	.goods-price-list {
		padding: 12px 16px 12px 16px;
		border-radius: 8px;
		background: #F5F5F5;
		margin: 10px auto;

		.goods-price-name {
			font-family: PingFang SC;
			font-size: 14px;
			font-weight: 400;
			line-height: 20px;
		}

		.price-num {
			font-family: PingFang SC;
			font-size: 14px;
			font-weight: 400;
			line-height: 20px;
			letter-spacing: 0px;
			text-align: right;
		}

		.price-item {
			margin-bottom: 10px;

			// padding: 0 10px;
			&:last-child {
				margin-bottom: 0;
			}
		}
	}

	.goods-details {
		height: 136px;
		padding: 12px;
		border-radius: 8px;
		background-color: #F5F5F5;
		font-family: PingFang SC;
		font-size: 14px;
		font-weight: 400;
		line-height: 20px;
		width: 100%;
		margin: 10px auto;
	}

	.goods-img {
		padding: 10px 0;

		.pick {
			font-size: 40px;
			// font-weight: 400;
			color: rgba(51, 51, 51, .61);
		}
	}

	.pop-box {
		// padding: 12px;
		margin: 20px;
		background-color: #ffffff;
		border-radius: 12px;

		.pop-alert {
			width: 20px;
			height: 20px;
			border-radius: 50%;
			background: #FCB513;
			text-align: center;
			font-size: 12px;
			color: #ffffff;
			line-height: 20px;
			margin: 20px 0 10px 0;
		}

		.pop-title {
			font-size: 16px;
			font-weight: 600;
			line-height: 24px;
			text-align: center;
			margin-bottom: 10px;
		}

		.pop-text {
			font-size: 12px;
			font-weight: 400;
			line-height: 18px;
			text-align: center;
			color: #898989;
			margin-bottom: 10px;
		}
	}

	.pop-btn-box {
		height: 44px;
		font-family: PingFang SC;
		font-size: 16px;
		font-weight: 400;
		line-height: 24px;
		text-align: center;
		border-top: 1px solid #e1e1e1;
		width: 100%;

		.pop-btn {
			height: 44px;
			width: 50%;
			box-sizing: border-box;
			color: rgba(51, 51, 51, .61);
			font-family: PingFang SC;
			font-size: 16px;
			font-weight: 400;
			line-height: 44px;
			letter-spacing: 0em;
			text-align: center;

			&.pop-red {
				color: #FA4543;
				border-left: 1px solid #e1e1e1;
			}
		}
	}
</style>